<script setup>
import router from "@/router/index.js";
import { ref } from "vue";
import {gsap} from "gsap";
import {ElMessageBox,ElMessage} from "element-plus";
import axios  from "axios";
import ChangePass from "@/views/User/components/changePass.vue";
// 返回登录页面的函数
const back = () => {
  router.push("/login")
}

// 控制猫动画的函数
const catMove = () => {
  gsap.timeline()
      .to(".cat", { duration: 0.5, y: -50, ease: "power2.out" }) // 向上跳跃
      .to(".cat", { duration: 0.5, rotation: 360, ease: "power2.in" }, "-=0.5") // 旋转
      .to(".cat", { duration: 0.5, y: 0, ease: "power2.in" }) // 回到原位
      .to(".cat", { duration: 0.5, scale: 1.2, ease: "power2.out" }, "-=0.5") // 放大
      .to(".cat", { duration: 0.5, scale: 1, ease: "power2.in" }); // 缩小回原大小
}

const input = ref("")
const emailInput = ref("")

let dialogFormVisible = ref(false)
let passwordFormVisible = ref(false)

// 提交账号或邮箱后弹出选择框
const handleSubmit = () => {
  if (input.value) {
    ElMessageBox.confirm(
        '请问是想密保找回还是邮箱找回呢？',
        '抉择！',
        {
          showClose: false,
          confirmButtonText: '密保！',
          cancelButtonText: '邮箱！',
          type: 'info',
        }
    )
        .then(() => {
          localStorage.setItem('forgetStore', input.value)
          //密保验证
          axios({
            method: 'get',
            baseURL:'http://localhost:8080',
            url:'/bind/question/get',
            params: {
              username: localStorage.getItem('forgetStore')
            },
          })
              .then((response) => {
                 console.log(response)
                 if (response.data.code === 10200){
                   console.log(response)
                   router.push("/find")
                }
                 else if (response.data.code === 104007){
                   ElMessage({
                     message: '无法查询到密保(请确保输入用户名或设置了密保）！',
                     type: 'warning',
                     duration: 2000,
                   })
                 }
              })

        })
        .catch(() => {
          //邮箱验证
          const config = {
            method: 'get',
            url: '/bind/email/get',
            baseURL: 'http://localhost:8080',
            params: {
              "usermessage": input.value,
            },
          }
          async function getEmailCode() {
            axios(config)
                .then((response) => {
                  if (response.data.code === 10200){
                    console.log(response)
                    ElMessage({
                      message: '验证码已发送至邮箱，请查收！',
                      type: 'success',
                      duration: 2000,
                    })
                    dialogFormVisible.value = true
                  }
                  else if (response.data.code === 10202){
                    console.log(response)
                    ElMessage({
                      message: '用户不存在！',
                      type: 'warning',
                      duration: 2000,
                    })
                  }

                })
                .catch((error) => {
                  console.log(error)
                  ElMessage({
                    message: '验证码发送失败，请稍后再试！',
                    type: 'error',
                    duration: 2000,
                  })
                })
          }
          getEmailCode()
        })}
   else {
    ElMessageBox.alert('请输入邮箱或账号哦~', '喵喵喵~', {
      confirmButtonText: '了解！',})
  }
}
// 取消验证的函数
const no = () => {
  dialogFormVisible.value = false
  ElMessage({
    message: '取消验证',
    type: 'warning',
    duration:  1000,
  })
}

let jwtToken = ref('');
// 确认验证的函数
const ok = () => {
  let formData = new FormData();
  formData.append('usermessage', input.value);
  formData.append('code', emailInput.value);
  const config = {
    method: 'post',
    url: '/bind/email/post',
    baseURL: 'http://localhost:8080',
    data: formData
  }
  async function submitEmailCode() {
    axios(config)
        .then((response) => {
          if (response.data.code === 10200){
            console.log(response)
            ElMessage({
              message: '验证通过！',
              type: 'success',
              duration: 2000,
            })
            dialogFormVisible.value = false;
            jwtToken = response.data.data.jwt_token;
            passwordFormVisible.value = true;
            console.log(jwtToken)
          }
          else if (response.data.code === 10402){
            console.log(response)
            ElMessage({
              message: '验证码错误！',
              type: 'warning',
              duration: 2000,
            })
          }
        })

        .catch((error) => {
          console.log(error)
          ElMessage({
            message: '验证失败！',
            type: 'error',
            duration: 2000,
          })
        })
  }
  submitEmailCode()
}


</script>

<template>
  <el-link class="iconfont icon-fanhui" :underline=false @click="back"></el-link>

  <div class="icon flex flex-col items-center justify-center mt-32">
    <img src="../../assets/icon/cat.png" alt="喵喵喵" class="cat" @click="catMove">
    <div>账号找不到了呜~</div>
  </div>

  <div class="flex items-center justify-center mt-20">
    <el-input v-model="input" style="width: 240px" placeholder="请输入邮箱或账号喵~" />
    <el-button type="primary" @click="handleSubmit">提交</el-button>
  </div>

  <el-dialog v-model="dialogFormVisible" title="邮箱验证码已发送" width="500">
    <el-form >
      <el-form-item label="请输入验证码" >
        <el-input v-model="emailInput" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="no">取消</el-button>
        <el-button type="primary" @click="ok">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <changePass :isShow=passwordFormVisible :jwtToken=jwtToken></changePass>

</template>

<style scoped>
.iconfont{
  font-size: 48px;
}
</style>